/*
 * Copyright (c) 2016. For Intelligent Group.
 */

package com.intelligent.mts.da.handler;

import com.intelligent.mts.da.message.ReceiveServerMessage;
import com.intelligent.mts.da.utils.Constant;
import com.intelligent.mts.da.utils.MessagesUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Julia.Zhou on 2016/07/20.
 */
public class AdapterClientHandler extends ChannelInboundHandlerAdapter {

    public static Logger logger = LoggerFactory.getLogger(AdapterClientHandler.class);
    private int requestId = 0;
    private int resultId = 0;
    private int dataId = 0;


    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String data = MessagesUtils.getCurrentData(requestId);
        String flow = "1010;OBC;"+ data +"#";
        ctx.writeAndFlush(flow);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("Receive msg" + msg);
        ReceiveServerMessage receiveMessage = MessagesUtils.decodeMessage((String) msg);
        String startFlag = receiveMessage.getStartFlag();

        ChannelPipeline p = ctx.pipeline();
        this.clearPipeline(p);
        switch(startFlag) {
            case Constant.START_VALIDATE_RESP :
                p.addLast("requestHandler", new RequestHandler(requestId));
                ctx.fireChannelRead(receiveMessage);
                requestId++;
                break;
            case Constant.START_STATUS_RESP:
                resultId++;
                p.addLast("resultHandler", new ResultHandler(resultId));
                ctx.fireChannelRead(receiveMessage);
                break;
            case Constant.START_DATA_RESP :
                p.addLast("dataHandler", new DataHandler(dataId));
                ctx.fireChannelRead(receiveMessage);
                dataId++;
                break;
            case Constant.START_HEAT :
                p.addLast("requestHandler", new RequestHandler(requestId));
                ctx.fireChannelRead(receiveMessage);
                requestId++;
                break;
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
       ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    private void clearPipeline(ChannelPipeline p)
    {
        if (p.get("requestHandler") != null) {
            p.remove("requestHandler");
        }
        if (p.get("resultHandler") != null) {
            p.remove("resultHandler");
        }
        if (p.get("dataHandler") != null) {
            p.remove("dataHandler");
        }
        if (p.get("dataHandler") != null) {
            p.remove("dataHandler");
        }
    }
}
